<template>
    <div class="scores-container">
        <el-card class="content-card">
            <div class="toolbar">
                <el-button type="primary" @click="dialogVisible = true">录入成绩</el-button>
                <el-input v-model="searchQuery" placeholder="搜索学生姓名" style="width: 200px; margin-left: 10px" />
            </div>

            <el-table :data="filteredScores" height="calc(100vh - 200px)">
                <el-table-column prop="studentId" label="学号" width="120" />
                <el-table-column prop="studentName" label="学生姓名" width="120" />
                <el-table-column prop="examId" label="考试编号" width="120" />
                <el-table-column prop="examName" label="考试名称" width="200" />
                <el-table-column prop="score" label="成绩" width="120" />
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
                        <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑成绩' : '录入成绩'">
            <el-form :model="scoreForm" :rules="rules" ref="formRef">
                <el-form-item label="学生" prop="studentId">
                    <el-select v-model="scoreForm.studentId" placeholder="选择学生" @change="handleStudentChange">
                        <el-option v-for="student in students" :key="student.id" :label="student.name"
                            :value="student.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="考试" prop="examId">
                    <el-select v-model="scoreForm.examId" placeholder="选择考试" @change="handleExamChange">
                        <el-option v-for="exam in exams" :key="exam.id" :label="exam.name" :value="exam.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="成绩" prop="score">
                    <el-input-number v-model="scoreForm.score" :min="0" :max="150" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { scoreApi, studentApi, examApi } from '@/api'

const scores = ref([])
const students = ref([])
const exams = ref([])
const dialogVisible = ref(false)
const isEdit = ref(false)
const currentId = ref(null)
const searchQuery = ref('')

const scoreForm = reactive({
    studentId: '',
    examId: '',
    score: 0,
    studentName: '',
    examName: ''
})

const rules = {
    studentId: [{ required: true, message: '请选择学生', trigger: 'change' }],
    examId: [{ required: true, message: '请选择考试', trigger: 'change' }],
    score: [{ required: true, message: '请输入成绩', trigger: 'blur' }]
}

// 获取所有需要的数据
const fetchAllData = async () => {
    try {
        // 模拟 API 调用
        const [scoresData, studentsData, examsData] = await Promise.all([
            scoreApi.getScores(),
            studentApi.getStudents(),
            examApi.getExams()
        ])

        // 模拟学生数据
    

        scores.value = scoresData
        students.value = studentsData
        exams.value = examsData
    } catch (error) {
        console.error('获取数据失败:', error)
    }
}

const filteredScores = computed(() => {
    if (!searchQuery.value) return scores.value
    return scores.value.filter(score =>
        score.studentName.toLowerCase().includes(searchQuery.value.toLowerCase())
    )
})

const handleStudentChange = (studentId) => {
    const student = students.value.find(s => s.id === studentId)
    if (student) {
        scoreForm.studentName = student.name
    }
}

const handleExamChange = (examId) => {
    const exam = exams.value.find(e => e.id === examId)
    if (exam) {
        scoreForm.examName = exam.name
    }
}

const handleEdit = (row) => {
    isEdit.value = true
    currentId.value = row.id
    Object.assign(scoreForm, row)
    dialogVisible.value = true
}

const handleDelete = (row) => {
    ElMessageBox.confirm('确定要删除该成绩记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            await scoreApi.deleteScore(row.id)
            ElMessage.success('删除成功')
            fetchAllData()
        } catch (error) {
            console.error('删除失败:', error)
        }
    }).catch(() => { })
}

const resetForm = () => {
    scoreForm.studentId = ''
    scoreForm.examId = ''
    scoreForm.score = 0
    scoreForm.studentName = ''
    scoreForm.examName = ''
    isEdit.value = false
    currentId.value = null
}

const handleSubmit = async () => {
    try {
        if (isEdit.value) {
            await scoreApi.updateScore(currentId.value, scoreForm)
            ElMessage.success('编辑成功')
        } else {
            await scoreApi.createScore(scoreForm)
            ElMessage.success('添加成功')
        }
        dialogVisible.value = false
        resetForm()
        fetchAllData()
    } catch (error) {
        console.error('操作失败:', error)
    }
}

// 页面加载时获取所有数据
fetchAllData()
</script>

<style scoped>
.scores-container {
    height: 100%;
    width: 100%;
}

.content-card {
    height: 100%;
}

.toolbar {
    margin-bottom: 20px;
}

:deep(.el-card__body) {
    height: 100%;
    padding: 20px;
}

:deep(.el-dialog__body) {
    padding-top: 10px;
}
</style>